package com.wzy.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 描述  :  复制 拷贝功能
 * 创建人:    Wzy
 * 创建时间: 2020-06-10  14:35
 */
public class NIOFileChannel03 {
    public static void main(String[] args) throws Exception {
        File file = new File("01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        FileChannel channel1 = fileInputStream.getChannel();

//        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        ByteBuffer buffer = ByteBuffer.allocate(512);


        FileOutputStream fileOutputStream = new FileOutputStream("02.txt");
        FileChannel channel2 = fileOutputStream.getChannel();

//        channel1.read(buffer);
//        buffer.flip();
//        channel2.write(buffer);
//
//        fileInputStream.close();
//        fileOutputStream.close();

        while (true) {
//            重置标志位，否则 position 位置位置有问题
            buffer.clear();
            int read = channel1.read(buffer);
            if (read == -1) break;

            buffer.flip();

            channel2.write(buffer);
        }
        fileInputStream.close();
        fileOutputStream.close();
    }
}
